package utils

import (
	"errors"
	"os"

	"gitee.com/knowgo/gpa"
	"gitee.com/knowgo/gpa/engine"
	"gitee.com/knowgo/gpa/engine/constants"
	"gitee.com/knowgo/gpa/engine/generator"
	"gitee.com/knowgo/gpa/logger"
	"gitee.com/knowgo/gpa/rt"
)

var e *engine.Engine
var g *generator.Generator
var p *rt.Provider

func GetProvider() *rt.Provider {
	if p == nil {
		var err error
		source, ok := os.LookupEnv("Database")
		if !ok {
			err = errors.New("请在环境变量中设置数据库连接: Database=数据库连接")
			panic(err)
		}
		p, err = gpa.NewProvider(constants.POSTGRES, source, nil)
		if err != nil {
			panic(err)
		}
	}
	return p
}

func GetGenerator() *generator.Generator {
	if g == nil {
		var err error
		g, err = gpa.NewGenerator(constants.POSTGRES, logger.GetLogger())
		if err != nil {
			panic(err)
		}
	}
	return g
}

func GetEngine() *engine.Engine {

	if e == nil {
		var err error
		source, ok := os.LookupEnv("Database")
		if !ok {
			err = errors.New("请在环境变量中设置数据库连接: Database=数据库连接")
			panic(err)
		}
		// source := os.Environ()
		e, err = gpa.NewEngine(constants.POSTGRES, source, nil)
		if err != nil {
			panic(err)
		}
	}
	return e
}
